package com.ruoyi.web.controller.system;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.UploadUtils;
import com.ruoyi.system.domain.bo.LcAttachmentBo;
import com.ruoyi.system.domain.bo.SysOssBo;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传 控制层
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/oss")
public class SysOssController extends BaseController {

    /**
     * 文件路径
     */
    private static String storePath = "C:\\Users\\Administrator\\Desktop\\nginx-1.18.0\\html\\resFiles";
//        本地
//    private static String storePath = "/Users/tzxin/Downloads/文档/图片";

    private final ISysOssService iSysOssService;

    /**
     * 查询OSS对象存储列表
     */
    @GetMapping("/list")
    public TableDataInfo<SysOssVo> list(@Validated(QueryGroup.class) SysOssBo bo, PageQuery pageQuery) {
        return iSysOssService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询OSS对象基于id串
     *
     * @param ossIds OSS对象ID串
     */
    @GetMapping("/listByIds/{ossIds}")
    public R<List<SysOssVo>> listByIds(@NotEmpty(message = "主键不能为空")
                                       @PathVariable Long[] ossIds) {
        List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(ossIds));
        return R.ok(list);
    }

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    /**
     * 下载OSS对象
     *
     * @param ossId OSS对象ID
     */
    @GetMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        iSysOssService.download(ossId, response);
    }

    /**
     * 删除OSS对象存储
     *
     * @param ossIds OSS对象ID串
     */
    @Log(title = "OSS对象存储", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ossIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ossIds) {
        return toAjax(iSysOssService.deleteWithValidByIds(Arrays.asList(ossIds), true));
    }

    @SaIgnore
    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<LcAttachmentBo> uploadFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 务必，防止返回文件名是乱码
            response.setCharacterEncoding("utf-8");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multipartRequest.getFileNames();

            while (iter.hasNext()) {
                MultipartFile file = multipartRequest.getFile(iter.next());
                LcAttachmentBo info = new LcAttachmentBo();
                if (file.isEmpty()) {
                    return R.fail(1, "上传文件不能为空");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
                String ymd = sdf.format(new Date());
                String savePath = storePath;
                //文件大小
                long fileSize = file.getSize();
                info.setFileSize(Long.toString(fileSize));
                if (fileSize > 100000000) {
                    return R.fail(1, "上传失败：文件大小不能超过100M");
                }
                //得到文件名称
                String fileName = file.getOriginalFilename();
                info.setOriginalName(fileName);
                String newFileName = "";
                String fileExt = "";
                String saveFileName = ymd;
                savePath += File.separator + ymd + File.separator;
                File dirFile = new File(savePath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                if (fileSize > 0) {
                    try {
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        //文件后缀
                        fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        info.setFileExt(fileExt);
                        //重定义文件名
                        newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                        info.setAttName(newFileName);
                        // 保存文件到本地
                        UploadUtils.saveFileFromInputStream(file.getInputStream(), savePath, newFileName);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                } else {
                    return R.fail(1, "上传失败：上传文件不能为空");
                }


                //保存入库
                saveFileName += File.separator + newFileName;

                info.setAddress(saveFileName);

                return R.ok("上传成功", info);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(1, "系统偷懒了");

        }
        return R.fail(1, "系统偷懒了");
    }

    @SaIgnore
    @PostMapping(value = "/uploadJsonFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<LcAttachmentBo> uploadJsonFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 务必，防止返回文件名是乱码
            response.setCharacterEncoding("utf-8");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multipartRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multipartRequest.getFile(iter.next());
                LcAttachmentBo info = new LcAttachmentBo();
                if (file.isEmpty()) {
                    return R.fail(1, "上传文件不能为空");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
                String ymd = sdf.format(new Date());
                String savePath = storePath;
                //文件大小
                long fileSize = file.getSize();
                info.setFileSize(Long.toString(fileSize));
                if (fileSize > 100000000) {
                    return R.fail(1, "上传失败：文件大小不能超过100M");
                }
                //得到文件名称
                String fileName = file.getOriginalFilename();
                info.setOriginalName(fileName);
                String newFileName = "";
                String fileExt = "";
                String saveFileName = ymd;
                savePath += File.separator + ymd + File.separator;
                File dirFile = new File(savePath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                if (fileSize > 0) {
                    try {
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        //文件后缀
                        fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        info.setFileExt(fileExt);
                        //重定义文件名
                        newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                        info.setAttName(newFileName);
                        // 保存文件到本地
                        UploadUtils.saveFileFromInputStream(file.getInputStream(), savePath, newFileName);
                        // 将表单数据插入到数据库中
                        InputStream input = file.getInputStream();
                        StringBuilder sb = new StringBuilder();
                        byte[] buffer = new byte[1024];
                        int length = 0;
                        length = input.read(buffer);

                        while (length != -1) {
                            sb.append(new String(buffer, 0, length));
                            length = input.read(buffer);
                        }
                        //保存入库
                        saveFileName += File.separator + newFileName;
                        info.setAddress(saveFileName);

                        // 固定一个流程id
                        info.setAbout("202384658715251102");
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                } else {
                    return R.fail(1, "上传失败：上传文件不能为空");
                }
                return R.ok("上传成功", info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(1, "系统偷懒了");

        }
        return R.fail(1, "系统偷懒了");
    }

}
